package com.acwebsitedesign.uRateDrugs.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.acwebsitedesign.uRateDrugs.domain.Drug;
import com.acwebsitedesign.uRateDrugs.domain.DrugService;

@Controller
@SessionAttributes("editDrug")
public class EditDrugController {
	
	@Autowired
	DrugService drugService;
	
	@RequestMapping("/selectDrugToEdit.html")
	public ModelAndView selectDrugToEdit() {
		
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		if (!(username.contentEquals("admin"))){
			ModelAndView mav = new ModelAndView("redirect:uRateDrugs-webapp/spring_security_login");
			return mav;
		}

		Drug editDrug = new Drug();
		ModelAndView mav = new ModelAndView("selectDrugToEdit");
		mav.addObject("editDrug", editDrug);
		return mav;
	}
	
	@RequestMapping("/editDrug.html")
		public ModelAndView editDrug(@RequestParam int id, @ModelAttribute("editDrug") Drug drug) {
		
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		if (!(username.contentEquals("admin"))){
			ModelAndView mav = new ModelAndView("redirect:uRateDrugs-webapp/spring_security_login");
			return mav;
		}
		
		List<Drug> drugList= drugService.getDrugById(id);
		Drug editDrug = drugList.get(0);
		ModelAndView mav = new ModelAndView("editDrug");
		if (drugList.isEmpty()){
			return new ModelAndView("drugNotFound");
			} else {
		mav.addObject(editDrug);
		}
		return mav;
	}
	
	@RequestMapping("/editDrugComplete.html")
	public ModelAndView saveDrug (@ModelAttribute("editDrug") Drug drug) {
		
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		if (!(username.contentEquals("admin"))){
			ModelAndView mav = new ModelAndView("redirect:uRateDrugs-webapp/spring_security_login");
			return mav;
		}
		
		drugService.saveDrug(drug);		
		ModelAndView mav = new ModelAndView("saveDrug");
		return mav;
	}
	
	@RequestMapping("/addDrugAlias.html") 
	public ModelAndView addDrugAlias () {
		ModelAndView mav = new ModelAndView("addDrugAlias");
		return mav;
	}
	
	@RequestMapping("/saveDrugAlias.html") 
	public ModelAndView saveDrugAlias (@RequestParam String id, @RequestParam String alias) {
		ModelAndView mav = new ModelAndView("saveDrugAlias");
	    int drugId = Integer.parseInt(id);
		List<Drug> drugList = drugService.getDrugById(drugId);
		Drug drug = drugList.get(0);
		drugService.saveDrugAlias(drug, alias);
		return mav;
	}


	
}